from . import index_blueprint
from flask import render_template, session, request, jsonify,g
from info.models import User, Category, News
from info import constants
from info.response_code import RET
from info.utils.common import login_wrapps

@index_blueprint.route('/')
@login_wrapps
def index():
    # 用户状态
    # user_id = session.get('user_id')
    # if user_id is None:
    #     user = None
    # else:
    #     user = User.query.get(user_id).to_login_dict()
    # 分类信息
    category_list1 = Category.query.all()  # ===>[category,....]
    category_list2 = [category.to_dict() for category in category_list1]
    # 点击排行
    # news_list1 = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    # news_list2 = [news.to_click_dict() for news in news_list1]
    from info.utils.common import get_click_list
    news_list2=get_click_list()

    # 新闻列表

    data = {
        'user': g.user.to_login_dict(),
        'category_list': category_list2,
        'news_list': news_list2
    }
    return render_template(
        'news/index.html',
        data=data
    )


@index_blueprint.route('/newslist')
def newslist():
    # 接收：页码值，分类编号，页大小
    page = request.args.get('page')
    cid = request.args.get('cid')
    per_page = request.args.get('per_page')

    # 验证
    if not all([page, cid, per_page]):
        return jsonify(errno=RET.NODATA, errmsg='数据不完整')

    # 处理：分页查询paginate()
    pagination = News.query
    #当选中“最新”时，表示不指定分类，查询所有数据，cid=0表示最新
    if int(cid) != 0:
        pagination = pagination.filter_by(category_id=cid)
    pagination = pagination.order_by(News.id.desc()). \
        paginate(int(page), int(per_page), False)
    # 获取当前页的数据
    news_list1 = pagination.items
    # 获取总页数
    total_page = pagination.pages

    # 将新闻列表转换成html中需要的数据字典
    news_dict_list = [news.to_index_dict() for news in news_list1]

    # 响应
    data = {
        'errno': RET.OK,
        'errmg': '',
        'cid': cid,
        'current_page': page,
        'totalPage': total_page,
        'newsList': news_dict_list
    }

    return jsonify(data)
